<?php
// +----------------------------------------------------------------------
// | HkCms 全站配置管理
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\admin\controller\routine;

use app\admin\controller\BaseController;
use think\facade\Validate;

class Config extends BaseController
{
    /**
     * @var \app\admin\model\routine\Config
     */
    protected $model;

    protected $middleware = [
        'login',
        'auth' => ['except'=>['fieldGroup']]
    ];

    /**
     * 初始化操作
     */
    public function initialize()
    {
        parent::initialize();

        $this->model = new \app\admin\model\routine\Config();
    }

    public function index()
    {
        $group = $this->model->where(['name'=>'group'])->value('value');
        $group = json_decode($group, true);

        $list = $this->model->where('group','<>','group')->select()->toArray();
        $newList = [];
        foreach ($list as $k=>$v) {
            if (!empty($v['data_list'])) $v['data_list'] = json_decode($v['data_list'],true);
//            if ($v['type'] == 'checkbox' || $v['type'] == 'selects') $v['value'] = explode('|',$v['value']);
            $newList[$v['group']][] = $v;
        }
        $this->view->layout(false);
        foreach ($newList as &$v) {
            $v = $this->view->fetch('field', ['data'=>$v]);
        }

        $this->view->layout(true);
        $this->view->assign('lists',$newList);
        $this->view->assign('group',$group);
        $this->view->assign('tabs_page', $this->request->param('tabs_page','basics'));

        // 其他页转过来添加返回按钮
        $ref = $this->request->get('referer','');
        $this->view->assign('backBtn', $ref?1:0);
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $params['is_default'] = 0;
            $this->validate($params, [
                'type|'.lang('Field type') => 'require|alphaDash',
                'name|'.lang('Field') => 'require|alphaDash|max:20',
                'title|'.lang('Title') => 'require',
                'rules|'.lang('Rule') => 'max:255',
                'tips|'.lang('Tips') => 'max:255',
                'error_tips|'.lang('Error message') => 'max:255',
                'extend|'.lang('HTML attributes') => 'max:500',
            ]);

            // 判断是否已经存在
            if ($this->model->where(['name'=>$params['name']])->value('id')) {
                $this->error(lang('Key name already exists'));
            }
            // 最大数量判断
            if (in_array($params['type'], ['images','downfiles']) && !is_numeric($params['max_number'])) {
                $this->error(lang('Maximum number format error'));
            }
            if ('number' == $params['type'] && !is_numeric($params['value'])) {
                $this->error(lang("The default value must be a number"));
            } else if ('datetime' == $params['type'] && !Validate::dateFormat($params['value'],'Y-m-d H:i:s')) {
                $this->error(lang("The default value must be in date time format"));
            } else if ('date' == $params['type'] && !Validate::dateFormat($params['value'],'Y-m-d')) {
                $this->error(lang('The default value must be date'));
            }

            if (in_array($params['type'], ['radio','checkbox','select','selects'])) {
                $data_list = explode("\r\n", $params['data_list']);
                $datalist = [];
                foreach ($data_list as $k => $v) {
                    $arr = explode('|',$v);
                    if (count($arr) != 2) {
                        $this->error(lang('Data list format error'));
                    }
                    $datalist[$arr[0]] = $arr[1];
                }
                $params['data_list'] = json_encode($datalist);
            }

            $this->model->insert($params);
            $this->success();
        }
        return $this->view->fetch();
    }

    public function edit($id = null)
    {
        $data = input('post.');
        //修改基础配置、邮件配置数据
        foreach ($data['row'] as $k=>$v) {
            if (is_array($v)) {
                $v = implode('|',$v);//暂定复选结果
            }
            $this->model->where('name',$k)->update(['value'=>$v]);
        }

        if (isset($data['group']) && isset($data['group']['key']) && isset($data['group']['value'])) {
            $keys = $data['group']['key'];
            $values = $data['group']['value'];
            $add = [];
            foreach ($keys as $key=>$value) {
                $add[$value] = $values[$key];
            }
            $this->model->where(['name'=>'group'])->save(['value'=>json_encode($add)]);
        }

        $this->model::initConfig(true);
        $this->success();
    }

    /**
     * 字段分组
     * @return \think\response\Json
     */
    public function fieldGroup()
    {
        $searchValue = $this->request->param('searchValue', '');
        $name = $this->request->param('name', '');
        if (!empty($searchValue)) {
            return json(['rows'=>[['title'=>$searchValue]]]);
        }


        $data = $this->model->where(['name'=>'group'])->value('value');
        $data = json_decode($data, true);
        if (!empty($name) && !in_array($name, $data)) {
            array_push($data, $name);
        }

        $arr = [];
        foreach ($data as $key=>$value) {
            $arr[] = ['title'=>lang($value),'name'=>$key];
        }

        return json(['rows'=>$arr]);
    }
}